<script setup lang="ts">
import { ref, reactive } from "vue";
import {
  queryCategoryList,
  addCategory,
  updateCategory,
  deleteCategory
} from "@/api/service";
import { uploadUrl } from "@/api/global";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";

defineOptions({
  name: "service"
});
const currentPage = ref(1);
const pageSize = ref(10); // 添加这行

const pageTotal = ref(0);
let tableData = ref([]);
const type = ref("");
let previewUrl = ref("");
//初始化列表
queryListTableData();

//查询列表
function queryListTableData(params?) {
  const _params = {
    pageNo: 1,
    pageSize: 10,
    total: 0,
    ...params
  };
  queryCategoryList({ ..._params }).then((res: any) => {
    console.log(res, "res");
    tableData.value = res.data;
  });
}

//筛选
const ruleFormRef = ref<FormInstance>();

const validatesortNum = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入排序号"));
  } else {
    if (ruleForm.sortNum !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("sortNum");
    }
    callback();
  }
};
const ruleForm = reactive({
  sortNum: "",
  categoryName: "",
  imageUrl: ""
});

const rules = reactive<FormRules<typeof ruleForm>>({
  sortNum: [{ required: true, validator: validatesortNum, trigger: "blur" }],
  categoryName: [
    { required: true, message: "请输入分类名称", trigger: "blur" }
  ],
  imageUrl: [{ required: true, message: "请上传图片", trigger: "change" }]
});

//添加
const addRoleDialogVisible = ref(false);
// 在其他 ref 声明附近添加
// 在 handleAdd 函数中添加技能列表初始化
function handleAdd(mark) {
  addRoleDialogVisible.value = true;
  type.value = mark;
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = key === "skills" ? [] : "";
  });
}
function addRoleInfo() {
  addCategory({
    categoryName: ruleForm.categoryName,
    sortNum: ruleForm.sortNum,
    imageUrl: ruleForm.imageUrl
  })
    .then((res: any) => {
      console.log(res);
      ElMessage({
        type: "success",
        message: res.message
      });
      addRoleDialogVisible.value = false;
      queryListTableData();
    })
    .catch((err: any) => {
      console.log(err);
      ElMessage({
        type: "error",
        message: err.message
      });
    });
}
//编辑
const editId = ref("");
const handleEditRole = async (row, mark) => {
  console.log(row, "data");
  type.value = mark;
  editId.value = row.id;
  addRoleDialogVisible.value = true;
  ruleForm.sortNum = row.sortNum;
  ruleForm.categoryName = row.categoryName;
  ruleForm.imageUrl = row.imageUrl;
};
function editRoleInfo() {
  console.log(ruleForm, "ruleForm");
  // 处理图片URL
  const imageUrl = ruleForm.imageUrl.includes("https://www.itbenma.com/budcare")
    ? ruleForm.imageUrl.replace("https://www.itbenma.com/budcare", "")
    : ruleForm.imageUrl;
  updateCategory({
    categoryName: ruleForm.categoryName,
    sortNum: ruleForm.sortNum,
    imageUrl: imageUrl,
    id: editId.value
  }).then((res: any) => {
    console.log(res);
    addRoleDialogVisible.value = false;
    ElMessage({
      type: "success",
      message: res.message
    });
    queryListTableData();
  });
}
//提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      console.log("submit!");
      if (type.value == "add") {
        addRoleInfo();
      } else if (type.value == "edit") {
        editRoleInfo();
      }
    } else {
      console.log("error submit!");
    }
  });
};
//删除用户
const handleDeteleRole = async (record: Recordable) => {
  // const type = await VxeUI.modal.confirm("您确定要删除吗？");
  ElMessageBox.confirm("确认是否删除?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteCategory({ id: record.id })
        .then((res: any) => {
          console.log(res);
          ElMessage({
            type: "success",
            message: res.message
          });
          queryListTableData();
        })
        .catch((err: any) => {
          console.log(err);
          ElMessage({
            type: "error",
            message: err.message
          });
        });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "删除失败"
      // });
    });
};
//重置添加用户
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  queryListTableData(val);
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  queryListTableData(val);
};
function handleClose() {
  console.log("关闭");
  addRoleDialogVisible.value = false;
}
// 头像上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    console.log(response, "response");
    // 使用完整的URL路径
    ruleForm.imageUrl = response.data.dataUrl;
    uploadFile.url = response.data.previewUrl;
    previewUrl.value = uploadFile.url;
    console.log(ruleForm.imageUrl, uploadFile.url, "r");
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
</script>
<template>
  <div class="statement">
    <div class="add">
      <el-button type="primary" size="large" @click="handleAdd('add')"
        ><el-icon><Plus /></el-icon>添加分类</el-button
      >
    </div>
    <div class="c-page__bg">
      <el-table :data="tableData">
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column prop="id" label="分类ID" />
        <el-table-column prop="sortNum" label="排序号" />
        <el-table-column label="分类图片">
          <template #default="scope">
            <el-image
              :src="scope.row.imageUrl"
              fit="cover"              
              style="width: 50px; height: 50px; cursor: pointer;"
              :preview-src-list="[scope.row.imageUrl]"
              :initial-index="0"
              :hide-on-click-modal="true"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column #default="{ row }" label="操作" width="220">
          <span class="c-text-primary" @click="handleEditRole(row, 'edit')"
            >编辑</span
          >
          <span class="c-text-primary" @click="handleDeteleRole(row)">
            删除
          </span>
        </el-table-column>
      </el-table>
      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pageTotal"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="addRoleDialogVisible"
      title="添加分类信息"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="ruleForm.categoryName"
            type="text"
            autocomplete="off"
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input
            v-model="ruleForm.sortNum"
            type="sortNum"
            autocomplete="off"
            placeholder="请输入排序号"
          />
        </el-form-item>
        <el-form-item label="头像" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="uploadUrl"
            :data="{ type: 'avatar' }"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="ruleForm.imageUrl && !previewUrl"
              :src="ruleForm.imageUrl"
              class="avatar"
            />
            <img v-else-if="previewUrl" :src="previewUrl" class="avatar" />
            <div v-else>
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <div class="upload-text">请上传图片</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item
          v-if="type != 'detail'"
          label="  "
          style="margin-top: 30px"
        >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.statement {
  height: 100%;
  overflow: hidden;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.search {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 8px;
  display: flex;
  // align-items: center;
  flex-wrap: wrap;
  .c-input {
    width: 240px !important;
    margin-bottom: 16px;
    margin-right: 16px;
    --el-border-radius-base: 8px;
    --el-input-focus-border-color: var(--main-color) !important;
    --el-component-size: 40px;
  }

  .search-btn {
    padding-left: 15px;
    .c-btn {
      height: 38px;
      border-radius: 8px;
      box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
    }
  }
}

.c-page__bg {
  width: 100%;
  height: 100%;
  margin-top: 25px;
  padding-bottom: 24px;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.c-text-primary {
  font-size: 14px;
  color: #1c9fff;
  white-space: nowrap;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.pagination-block {
  padding-top: 20px;
  padding-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.c-dot-success,
.c-dot-info {
  width: 6px;
  height: 6px;
  margin-right: 6px;
  display: inline-block;
  border-radius: 50%;
  flex-shrink: 0;
  background-color: #43bf0a;
}

.c-dot-info {
  background-color: #bfbfbf;
}

.system-icon-content {
  min-height: 500px;
}

.flex-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #262626;
}

.back {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #1c9fff;

  .back-text {
    display: flex;
    align-items: center;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .title {
    color: #8c8c8c;
    font-size: 16px;
  }
}
.c-drawer-form {
  .c-info__title {
    margin-top: 20px;
    margin-bottom: 20px;
    color: #262626;
    font-size: 16px;
  }
  .el-form-item {
    margin-left: 60px;
    margin-bottonm: 10px;
  }
}
.el-drawer__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdcdc;
  margin-bottom: 0;
}
.upload-text {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

// ... 上传图片 ...

.avatar-uploader,
.qrcode-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.required-label::before {
  content: "*";
  color: var(--el-color-danger);
  margin-right: 4px;
}

// ... 其他样式 ...
.qrcode-uploader-icon,
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  text-align: center;
  line-height: 100px;
}

.qrcode,
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
